<!--
 * @Author: 小花
 * @Date: 2022-05-21 18:59:11
 * @LastEditors: 小花
 * @LastEditTime: 2022-05-28 17:57:17
 * @FilePath: /permission_client/src/views/LoginView.vue
 * @Description: 登录/注册
-->
<template>
  <div class="loginBox"><input type="text" placeholder="账号" v-model="form.account" />
    <br>
    <input type="password" placeholder="密码" v-model="form.password" />
    <br>
    <button @click="doLoginFn">登录</button>
    <button @click="doRegisterFn">注册</button>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs } from 'vue'
import { doLogin, doRegister } from '@/request'
import LoginView, { handlerMenu, IResultMap } from '@/model/LoginView'
import { responseEnum, responseUtil } from '@/request/responseUtil'
import router from '@/router'
import { ElMessage } from 'element-plus'
import { useStore } from '@/store'

export default defineComponent({
  name: 'LoginView',
  setup () {
    const store = useStore()
    const coreData = reactive(new LoginView())

    const doLoginFn = async () => {
      const result = await (await doLogin(coreData.form)).data as responseUtil<IResultMap>
      const redirect = router.currentRoute.value.query.redirect as string || '/'
      if (result.code === responseEnum.LOGIN_SUCCESS) {
        ElMessage.success('登录成功')
        store.loginInfo.satoken = result.data.satoken
        const children = result.data.routes.filter(it => it.parentId)
        const parent = result.data.routes.filter(it => !it.parentId)
        handlerMenu(children, parent)
        store.loginInfo.routes = parent
        store.loginInfo.originalRoutes = result.data.routes
        router.replace(redirect)
      } else if (result.code === responseEnum.LOGIN_INFO_ERROR) {
        ElMessage.error('账号或密码错误')
      } else if (result.code === responseEnum.LOGIN_VALID) {
        router.replace(redirect)
      }
    }

    const doRegisterFn = async () => {
      const result = await (await doRegister(coreData.form)).data as responseUtil
      if (result.code === responseEnum.REGISTER_SUCCESS) {
        ElMessage.success('注册成功')
      } else if (result.code === responseEnum.FAIL) {
        ElMessage.error(result.msg)
      }
    }

    return {
      ...toRefs(coreData),
      doLoginFn,
      doRegisterFn
    }
  }
})
</script>

<style lang="scss" scoped>
.loginBox {
  text-align: center;
}
</style>
